from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

# chromedriver路径
driver_path = "D:\\pycharm\\PM_test\\chromedriver.exe"
service = Service(driver_path)
options = Options()
browser = webdriver.Chrome(service=service, options=options)
browser.maximize_window()
wait = WebDriverWait(browser, 10)

# 登录函数
def login():
    browser.get("http://146.56.217.9:9131")
    wait.until(EC.presence_of_element_located((By.ID, "username"))).send_keys("admin_9131")
    browser.find_element(By.ID, "password").send_keys("admin")
    browser.find_element(By.CLASS_NAME, "button").click()
    wait.until(EC.presence_of_element_located((By.ID, "mainmenutd_products")))
def go_to_batch_number_creation():
    browser.find_element(By.ID, "mainmenutd_products").click()
    browser.find_element(By.CSS_SELECTOR, '.menu_contenu_product_stock_productlot_list .vsmenu').click()


def add_batch_number(data: dict):
    """
    添加批号记录
    :param data: 包含 product_index, batch, sellby, eatby 的字典
    """
    # 进入添加页面
    browser.find_element(By.CSS_SELECTOR, ".btnTitlePlus").click()

    # 选择产品
    browser.find_element(
        By.CSS_SELECTOR,
        f"select#fk_product > option:nth-child({data['product_index']})"
    ).click()

    # 填写表单字段
    browser.find_element(By.ID, "batch").send_keys(data['batch'])
    browser.find_element(By.ID, "sellby").send_keys(data['sellby'])
    browser.find_element(By.ID, "eatby").send_keys(data['eatby'])

    # 提交
    browser.find_element(By.NAME, "add").click()


if __name__ == '__main__':
    try:
        login()
        test_data_list = [
            {"product_index": 2, "batch": "001", "sellby": "2025/06/03", "eatby": "2025/06/30"},#正向测试
            {"product_index": 2, "batch": "002", "sellby": "2025/06/04", "eatby": "20250701"},#反向测试,保质期格式不规范
            {"product_index": 2, "batch": "002", "sellby": "2025/06/04", "eatby": "2025/07/01"},#反向测试，序列号一样
            {"product_index": 2, "batch": "003", "sellby": "20250605", "eatby": "2025/07/08"}#反向测试，销售日期格式不规范
        ]

        for data in test_data_list:
            go_to_batch_number_creation()
            add_batch_number(data)
            sleep(7)
    except Exception as e:
        print("出错了：", type(e).__name__, str(e))
    finally:
        sleep(1)
        browser.quit()
